<?php
namespace common\service;

use chonder\AliyunOSS\AliyunOSS;
use Yii;

class OssService {

    private $ossClient;

    public function __construct($isInternal = false)
    {
        $serverAddress = $isInternal ? Yii::$app->params['oss']['ossServerInternal'] : Yii::$app->params['oss']['ossServer'];
        $this->ossClient = AliyunOSS::boot(
            $serverAddress,
            Yii::$app->params['oss']['AccessKeyId'],
            Yii::$app->params['oss']['AccessKeySecret']
        );
    }

    /**
     * @param $ossKey
     * @param $filePath
     * @param $content_type_tag  true设置content_type false 不设置content
     */
    public static function upload($ossKey, $filePath,$content_type_tag)
    {
        //$oss = new OSS(true); // 上传文件使用内网，免流量费
        $oss = new OssService();

        if($content_type_tag==true){
            $finfo    = finfo_open(FILEINFO_MIME);
            $mimetype = finfo_file($finfo, $filePath);
            finfo_close($finfo);
        }else{
            $mimetype = null ;
        }

        $oss->ossClient->setBucket(Yii::$app->params['oss']['Bucket']);
        $oss->ossClient->uploadFile($ossKey, $filePath,$mimetype);
    }

    public static function getUrl($ossKey)
    {
        $oss = new OssService();
        $oss->ossClient->setBucket(Yii::$app->params['oss']['Bucket']);
        return preg_replace('/(.*)\?OSSAccessKeyId=.*/', '$1', $oss->ossClient->getUrl($ossKey, new \DateTime("+1 day")));
    }

    public static function delFile($ossKey)
    {
        $oss = new OssService();
        $oss->ossClient->setBucket(Yii::$app->params['oss']['Bucket']);
        $oss->ossClient->delFile($ossKey);
    }

    public static function createBucket($bucketName)
    {
        $oss = new OssService();
        return $oss->ossClient->createBucket($bucketName);
    }

    public static function getAllObjectKey($bucketName)
    {
        $oss = new OssService();
        return $oss->ossClient->getAllObjectKey($bucketName);
    }

}